package com.huhao.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CountDownLatchExample1 {

    //线程总数
    public static int threadTotal = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(threadTotal);
        for (int index = 0; index < threadTotal; index++) {
            final int threadNum = index;
            exec.execute(() -> {
                try {
                    add(threadNum);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        //保证线程减到0,保证最后finish打印是在所有线程执行完才会执行
        countDownLatch.await();
        //只等待10毫秒，超过了就不管之后线程的执行了，直接执行之后的代码，打印finish
        // （之后的线程还是会正常执行完的，只是await之后的代码会在到期之后立马执行）
//        countDownLatch.await(10, TimeUnit.MICROSECONDS);

        //等已有线程都执行完，再关闭线程池
        exec.shutdown();
        log.error("finish");
    }

    private static void add(int threadNum) throws InterruptedException {
        Thread.sleep(100);
        log.info("{}", threadNum);
        Thread.sleep(100);
    }
}
